<?php

namespace app\common\service;

use app\common\model\Dict;
use app\http\exception\AuthException;

use function cache;

class DictService extends BaseService {
    public function getDictPage($data) {
        return Dict::build()
                   ->orderBy('dict_id', 'desc')
                   ->_paginate();
    }

    public function getDictList($data) {
        return Dict::build()
                   ->orderBy('dict_id', 'desc')
                   ->select();
    }

    public function getDictItem($id) {
        return Dict::build()
                   ->findOrFail($id);
    }

    public function delDictItem($ids) {
        return Dict::build()
                   ->whereIn('dict_id', $ids)
                   ->delete();
    }

    public function setDictItem($data, $id) {
        $info = Dict::build()
                    ->findOrFail($id);
        if (!$info) {
            throw new AuthException('数据不存在');
        }

        return $info->save($data);
    }


    public function addDictItem($data) {
        $model = new Dict();
        return $model->save($data);
    }

    public function getDictTree() : array {

        $tree = cache(CacheService::DICT_TREE_KEY);

        if(!$tree){
            $dict = Dict::where('status', 1)
                        ->select();
            $tree = [];
            foreach ($dict as $k => $v) {
                if ($v['pid'] == 0) {
                    $tmp['data_type'] = $v['data_type'];
                    $tmp['dict_id'] = $v['dict_id'];
                    $tmp['data_value'] = $v['data_value'];
                    $tmp['data_name'] = $v['data_name'];
                    $tmp['pid'] = $v['pid'];
                    $tree[$v['data_type']] = $tmp;
                    unset($dict[$k]);
                }
            }
            foreach ($tree as &$v) {
                foreach ($dict as $kk => $vv) {
                    if ($vv['pid'] == $v['dict_id']) {
                        $key = sprintf('%s_%s',$vv['data_type'], $vv['data_value']);
                        $v[$key] = $vv;
                        unset($dict[$kk]);
                    }
                }
            }
            cache(CacheService::DICT_TREE_KEY ,$tree , CacheService::DICT_TREE_EXPIRE );
        }


        return $tree;
    }

}
